const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;
const multer = require('multer');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 数据目录
const DATA_DIR = path.join(__dirname, 'data');

// 确保数据目录存在
async function ensureDataDir() {
    try {
        await fs.access(DATA_DIR);
    } catch {
        await fs.mkdir(DATA_DIR, { recursive: true });
    }
}

// 读取数据文件
async function readDataFile(filename) {
    try {
        const filePath = path.join(DATA_DIR, filename);
        const data = await fs.readFile(filePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        if (error.code === 'ENOENT') {
            return [];
        }
        throw error;
    }
}

// 写入数据文件
async function writeDataFile(filename, data) {
    const filePath = path.join(DATA_DIR, filename);
    await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf8');
}

// 生成唯一ID
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 检查延期项目
function checkOverdue(items, dateField, type) {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    return items.filter(item => {
        if (!item[dateField]) return false;
        const dueDate = new Date(item[dateField]);
        dueDate.setHours(0, 0, 0, 0);
        return dueDate < today;
    }).map(item => ({
        ...item,
        type: type,
        dueDate: item[dateField]
    }));
}

// 工作进度计划API
app.get('/api/work-plan', async (req, res) => {
    try {
        const data = await readDataFile('work-plan.json');
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

app.post('/api/work-plan', async (req, res) => {
    try {
        const data = await readDataFile('work-plan.json');
        const newItem = {
            id: generateId(),
            ...req.body,
            createdAt: new Date().toISOString()
        };
        data.push(newItem);
        await writeDataFile('work-plan.json', data);
        res.json(newItem);
    } catch (error) {
        res.status(500).json({ error: '创建失败' });
    }
});

app.put('/api/work-plan/:id', async (req, res) => {
    try {
        const data = await readDataFile('work-plan.json');
        const index = data.findIndex(item => item.id === req.params.id);
        if (index === -1) {
            return res.status(404).json({ error: '记录不存在' });
        }
        data[index] = { ...data[index], ...req.body };
        await writeDataFile('work-plan.json', data);
        res.json(data[index]);
    } catch (error) {
        res.status(500).json({ error: '更新失败' });
    }
});

app.delete('/api/work-plan/:id', async (req, res) => {
    try {
        const data = await readDataFile('work-plan.json');
        const filteredData = data.filter(item => item.id !== req.params.id);
        await writeDataFile('work-plan.json', filteredData);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '删除失败' });
    }
});

app.get('/api/work-plan/search', async (req, res) => {
    try {
        const data = await readDataFile('work-plan.json');
        const query = req.query.q?.toLowerCase() || '';
        const filtered = data.filter(item => 
            item.model?.toLowerCase().includes(query) ||
            item.workOrder?.toLowerCase().includes(query) ||
            item.remark?.toLowerCase().includes(query)
        );
        res.json(filtered);
    } catch (error) {
        res.status(500).json({ error: '搜索失败' });
    }
});

// 外发清单API
app.get('/api/outsource', async (req, res) => {
    try {
        const data = await readDataFile('outsource.json');
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

app.post('/api/outsource', async (req, res) => {
    try {
        const data = await readDataFile('outsource.json');
        const newItem = {
            id: generateId(),
            ...req.body,
            createdAt: new Date().toISOString()
        };
        data.push(newItem);
        await writeDataFile('outsource.json', data);
        res.json(newItem);
    } catch (error) {
        res.status(500).json({ error: '创建失败' });
    }
});

app.put('/api/outsource/:id', async (req, res) => {
    try {
        const data = await readDataFile('outsource.json');
        const index = data.findIndex(item => item.id === req.params.id);
        if (index === -1) {
            return res.status(404).json({ error: '记录不存在' });
        }
        data[index] = { ...data[index], ...req.body };
        await writeDataFile('outsource.json', data);
        res.json(data[index]);
    } catch (error) {
        res.status(500).json({ error: '更新失败' });
    }
});

app.delete('/api/outsource/:id', async (req, res) => {
    try {
        const data = await readDataFile('outsource.json');
        const filteredData = data.filter(item => item.id !== req.params.id);
        await writeDataFile('outsource.json', filteredData);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '删除失败' });
    }
});

app.get('/api/outsource/search', async (req, res) => {
    try {
        const data = await readDataFile('outsource.json');
        const query = req.query.q?.toLowerCase() || '';
        const filtered = data.filter(item => 
            item.model?.toLowerCase().includes(query) ||
            item.name?.toLowerCase().includes(query) ||
            item.location?.toLowerCase().includes(query)
        );
        res.json(filtered);
    } catch (error) {
        res.status(500).json({ error: '搜索失败' });
    }
});

// 数据查询API
app.get('/api/data-query', async (req, res) => {
    try {
        const data = await readDataFile('data-query.json');
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

app.post('/api/data-query', async (req, res) => {
    try {
        const data = await readDataFile('data-query.json');
        const newItem = {
            id: generateId(),
            ...req.body,
            createdAt: new Date().toISOString()
        };
        data.push(newItem);
        await writeDataFile('data-query.json', data);
        res.json(newItem);
    } catch (error) {
        res.status(500).json({ error: '创建失败' });
    }
});

app.put('/api/data-query/:id', async (req, res) => {
    try {
        const data = await readDataFile('data-query.json');
        const index = data.findIndex(item => item.id === req.params.id);
        if (index === -1) {
            return res.status(404).json({ error: '记录不存在' });
        }
        data[index] = { ...data[index], ...req.body };
        await writeDataFile('data-query.json', data);
        res.json(data[index]);
    } catch (error) {
        res.status(500).json({ error: '更新失败' });
    }
});

app.delete('/api/data-query/:id', async (req, res) => {
    try {
        const data = await readDataFile('data-query.json');
        const filteredData = data.filter(item => item.id !== req.params.id);
        await writeDataFile('data-query.json', filteredData);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '删除失败' });
    }
});

app.get('/api/data-query/search', async (req, res) => {
    try {
        const data = await readDataFile('data-query.json');
        const query = req.query.q?.toLowerCase() || '';
        const filtered = data.filter(item => 
            item.workOrder?.toLowerCase().includes(query) ||
            item.model?.toLowerCase().includes(query) ||
            item.partNumber?.toLowerCase().includes(query)
        );
        res.json(filtered);
    } catch (error) {
        res.status(500).json({ error: '搜索失败' });
    }
});

app.put('/api/data-query/:id/status', async (req, res) => {
    try {
        const data = await readDataFile('data-query.json');
        const index = data.findIndex(item => item.id === req.params.id);
        if (index === -1) {
            return res.status(404).json({ error: '记录不存在' });
        }
        
        const { statusType, status } = req.body;
        data[index][statusType] = status;
        await writeDataFile('data-query.json', data);
        res.json(data[index]);
    } catch (error) {
        res.status(500).json({ error: '更新状态失败' });
    }
});

// 钢网追踪API
app.get('/api/steel-mesh', async (req, res) => {
    try {
        const data = await readDataFile('steel-mesh.json');
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

app.post('/api/steel-mesh', async (req, res) => {
    try {
        const data = await readDataFile('steel-mesh.json');
        const newItem = {
            id: generateId(),
            ...req.body,
            createdAt: new Date().toISOString()
        };
        data.push(newItem);
        await writeDataFile('steel-mesh.json', data);
        res.json(newItem);
    } catch (error) {
        res.status(500).json({ error: '创建失败' });
    }
});

app.put('/api/steel-mesh/:id', async (req, res) => {
    try {
        const data = await readDataFile('steel-mesh.json');
        const index = data.findIndex(item => item.id === req.params.id);
        if (index === -1) {
            return res.status(404).json({ error: '记录不存在' });
        }
        data[index] = { ...data[index], ...req.body };
        await writeDataFile('steel-mesh.json', data);
        res.json(data[index]);
    } catch (error) {
        res.status(500).json({ error: '更新失败' });
    }
});

app.delete('/api/steel-mesh/:id', async (req, res) => {
    try {
        const data = await readDataFile('steel-mesh.json');
        const filteredData = data.filter(item => item.id !== req.params.id);
        await writeDataFile('steel-mesh.json', filteredData);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '删除失败' });
    }
});

app.get('/api/steel-mesh/search', async (req, res) => {
    try {
        const data = await readDataFile('steel-mesh.json');
        const query = req.query.q?.toLowerCase() || '';
        const filtered = data.filter(item => 
            item.model?.toLowerCase().includes(query) ||
            item.status?.toLowerCase().includes(query)
        );
        res.json(filtered);
    } catch (error) {
        res.status(500).json({ error: '搜索失败' });
    }
});

// 治具追踪API
app.get('/api/fixture', async (req, res) => {
    try {
        const data = await readDataFile('fixture.json');
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

app.post('/api/fixture', async (req, res) => {
    try {
        const data = await readDataFile('fixture.json');
        const newItem = {
            id: generateId(),
            ...req.body,
            createdAt: new Date().toISOString()
        };
        data.push(newItem);
        await writeDataFile('fixture.json', data);
        res.json(newItem);
    } catch (error) {
        res.status(500).json({ error: '创建失败' });
    }
});

app.put('/api/fixture/:id', async (req, res) => {
    try {
        const data = await readDataFile('fixture.json');
        const index = data.findIndex(item => item.id === req.params.id);
        if (index === -1) {
            return res.status(404).json({ error: '记录不存在' });
        }
        data[index] = { ...data[index], ...req.body };
        await writeDataFile('fixture.json', data);
        res.json(data[index]);
    } catch (error) {
        res.status(500).json({ error: '更新失败' });
    }
});

app.delete('/api/fixture/:id', async (req, res) => {
    try {
        const data = await readDataFile('fixture.json');
        const filteredData = data.filter(item => item.id !== req.params.id);
        await writeDataFile('fixture.json', filteredData);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '删除失败' });
    }
});

app.get('/api/fixture/search', async (req, res) => {
    try {
        const data = await readDataFile('fixture.json');
        const query = req.query.q?.toLowerCase() || '';
        const filtered = data.filter(item => 
            item.model?.toLowerCase().includes(query) ||
            item.status?.toLowerCase().includes(query)
        );
        res.json(filtered);
    } catch (error) {
        res.status(500).json({ error: '搜索失败' });
    }
});

// SOP签核追踪API
app.get('/api/sop', async (req, res) => {
    try {
        const data = await readDataFile('sop.json');
        res.json(data);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

app.post('/api/sop', async (req, res) => {
    try {
        const data = await readDataFile('sop.json');
        const newItem = {
            id: generateId(),
            ...req.body,
            createdAt: new Date().toISOString()
        };
        data.push(newItem);
        await writeDataFile('sop.json', data);
        res.json(newItem);
    } catch (error) {
        res.status(500).json({ error: '创建失败' });
    }
});

app.put('/api/sop/:id', async (req, res) => {
    try {
        const data = await readDataFile('sop.json');
        const index = data.findIndex(item => item.id === req.params.id);
        if (index === -1) {
            return res.status(404).json({ error: '记录不存在' });
        }
        data[index] = { ...data[index], ...req.body };
        await writeDataFile('sop.json', data);
        res.json(data[index]);
    } catch (error) {
        res.status(500).json({ error: '更新失败' });
    }
});

app.delete('/api/sop/:id', async (req, res) => {
    try {
        const data = await readDataFile('sop.json');
        const filteredData = data.filter(item => item.id !== req.params.id);
        await writeDataFile('sop.json', filteredData);
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '删除失败' });
    }
});

app.get('/api/sop/search', async (req, res) => {
    try {
        const data = await readDataFile('sop.json');
        const query = req.query.q?.toLowerCase() || '';
        const filtered = data.filter(item => 
            item.model?.toLowerCase().includes(query) ||
            item.status?.toLowerCase().includes(query)
        );
        res.json(filtered);
    } catch (error) {
        res.status(500).json({ error: '搜索失败' });
    }
});

// 延期检查API
app.get('/api/overdue', async (req, res) => {
    try {
        const workPlanData = await readDataFile('work-plan.json');
        const steelMeshData = await readDataFile('steel-mesh.json');
        const fixtureData = await readDataFile('fixture.json');
        const sopData = await readDataFile('sop.json');
        
        const overdueItems = [
            ...checkOverdue(workPlanData, 'date', '工作进度'),
            ...checkOverdue(steelMeshData, 'acceptanceDate', '钢网'),
            ...checkOverdue(fixtureData, 'acceptanceDate', '治具'),
            ...checkOverdue(sopData, 'approvalCompleteDate', 'SOP签核')
        ];
        
        res.json(overdueItems);
    } catch (error) {
        res.status(500).json({ error: '检查延期失败' });
    }
});

// 导入导出API
app.post('/api/import/:type', async (req, res) => {
    try {
        const { type } = req.params;
        const data = req.body;
        
        const filenameMap = {
            'work-plan': 'work-plan.json',
            'outsource': 'outsource.json',
            'data-query': 'data-query.json',
            'steel-mesh': 'steel-mesh.json',
            'fixture': 'fixture.json',
            'sop': 'sop.json'
        };
        
        const filename = filenameMap[type];
        if (!filename) {
            return res.status(400).json({ error: '不支持的导入类型' });
        }
        
        // 验证数据格式
        if (!Array.isArray(data)) {
            return res.status(400).json({ error: '数据格式错误' });
        }
        
        // 为每个项目添加ID
        const processedData = data.map(item => ({
            ...item,
            id: item.id || generateId()
        }));
        
        await writeDataFile(filename, processedData);
        res.json({ success: true, count: processedData.length });
    } catch (error) {
        res.status(500).json({ error: '导入失败' });
    }
});

app.get('/api/export/:type/:format', async (req, res) => {
    try {
        const { type, format } = req.params;
        
        const filenameMap = {
            'work-plan': 'work-plan.json',
            'outsource': 'outsource.json',
            'data-query': 'data-query.json',
            'steel-mesh': 'steel-mesh.json',
            'fixture': 'fixture.json',
            'sop': 'sop.json'
        };
        
        const filename = filenameMap[type];
        if (!filename) {
            return res.status(400).json({ error: '不支持的导出类型' });
        }
        
        const data = await readDataFile(filename);
        
        if (format === 'json') {
            res.setHeader('Content-Type', 'application/json');
            res.setHeader('Content-Disposition', `attachment; filename="${type}-${Date.now()}.json"`);
            res.send(JSON.stringify(data, null, 2));
        } else if (format === 'csv') {
            // 简化的CSV导出
            if (data.length === 0) {
                return res.status(400).json({ error: '没有数据可导出' });
            }
            
            const headers = Object.keys(data[0]);
            const csvContent = [
                headers.join(','),
                ...data.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
            ].join('\n');
            
            res.setHeader('Content-Type', 'text/csv');
            res.setHeader('Content-Disposition', `attachment; filename="${type}-${Date.now()}.csv"`);
            res.send('\ufeff' + csvContent);
        } else {
            res.status(400).json({ error: '不支持的导出格式' });
        }
    } catch (error) {
        res.status(500).json({ error: '导出失败' });
    }
});

// 初始化数据目录
ensureDataDir().then(() => {
    app.listen(PORT, () => {
        console.log(`服务器运行在 http://localhost:${PORT}`);
    });
});
